<!-- 课程评价 -->
<template>
    <div class="course-comment-container">
        <!-- 只有购买的用户才能评价 评价数据从问卷获取 预览的状态下，一直显示添加评价的模块，是未评价的状态，点击添加评价按钮给统一提示-->
        <template v-if="(isBuyPerson || isPreview) && assessAppraiseId">
            <MyComment v-if="isComment && !isPreview" :data="MyCommentContent"/>
            <AddComment v-else :data="MyCommentContent" :assess-info="assessInfo" :is-need-comment="isNeedComment" :is-preview="isPreview" @refresh-detail="emit('refresh-detail')"/>
            <el-divider class="divider-line"></el-divider>
        </template>
        <p class="comment-header">全部评价<span>({{data.total}})</span></p>
        <CommentList
            class="mar-t10"
            :data="data.list"
            :has-more="data.hasMore"
            :is-creater="isCreater"
            :assess-appraise-id="assessAppraiseId"
            :is-preview="isPreview"
            @update:list="toFirstPage(true)"/>
    </div>
</template>

<script setup>
import AddComment from './comment/add.vue';
import CommentList from './comment/index.vue';
import MyComment from './comment/my-comment.vue';
import { ref, reactive, onBeforeUnmount, watch, nextTick, computed } from 'vue';
import { Throttle } from '@/lib/tools';
import { useRoute } from 'vue-router';
import { useStore } from 'vuex';

const store = useStore();

const route = useRoute();

const emit = defineEmits(['refresh-detail']);

const props = defineProps({
    currentTab: {
        type: String,
        default: ''
    },
    detail: {
        type: Object,
        default: () => {
            return {};
        }
    },
    isBuyPerson: { // 是否有权限
        type: Boolean,
        default: false
    },
    isCreater: {
        type: Boolean,
        default: false
    },
    isPreview: { // 是否是预览状态
        type: Boolean,
        default: false 
    }
});

let currentTabKey = ref('CourseComment');

const assessInfo = ref({});

// 我的评论内容
const MyCommentContent = ref({});

// 是否已经提交过评价
const isComment = computed(() => {
    return MyCommentContent.value?.assessUser || false;
})

// 问卷id
const assessAppraiseId = computed(() => {
    return props.detail?.assessAppraiseId || ''
})

const data = reactive({
    list: [],
    hasMore: true,
    total: 0
})

const pageIndex = ref(1);

// 是否需要评价才算完成慕课
const isNeedComment = ref(false);

// 获取评论列表
function getComments () {
    if (!route.params.moocId || !Object.keys(props.detail).length || !props.detail.assessAppraiseId || !data.hasMore) {
        return false
    }
    G_transmit('courseCommentList', {
        data: {
            assessAppraiseId: props.detail.assessAppraiseId,
            moocId: route.params.moocId,
            pageIndex: pageIndex.value
        }
    }).then((res) => {
        data.total = res?.data?.total || 0;
		if (data.list.length <= data.total) {
			data.list = [...data.list, ...(res?.data?.rows || [])];
		}
        if (data.list.length >= data.total) {
		    data.hasMore = false;
        }
    })
}

// 划到底部加载动态
const handleScroll = Throttle(function (e) {
	let scrollTop =
		document.documentElement.scrollTop || document.body.scrollTop
	let clientHeight = document.documentElement.clientHeight
	let scrollHeight = document.documentElement.scrollHeight
	if (scrollTop + clientHeight >= scrollHeight - 300 && data.hasMore) {
		pageIndex.value++;
		getComments();
	}
}, 800)

// 获取评论模板信息
function getCommentTemplate () {
    // 慕课id不存在、慕课问卷id不存在或者是管理员不能评价
    if (!route.params.moocId && !Object.keys(props.detail).length || !props.detail.assessAppraiseId) {
        return false
    }
    assessInfo.value = {
        assessId: props.detail.assessAppraiseId,
        subBizId: route.params.moocId || '',
        subBizType: 'mooc',
        // queryInvalid: true // 查询包括删除的
    }
    G_transmit('queryAssessAnswer', {
        queries: assessInfo.value
    }).then((res) => {
        MyCommentContent.value = res.data || {};
    })
}

// 更新评论后到第一页并更新自己的模板数据 
function toFirstPage () {
    window.removeEventListener('scroll', handleScroll);
    pageIndex.value = 1;
    data.list = [];
    data.hasMore = true;
    if (props.detail?.assessAppraiseId) {
        getCommentTemplate();
    }
    getComments();
    nextTick(() => {
		window.addEventListener('scroll', handleScroll, true)
	})
}

// 获取慕课配置
function getMoocConfig () {
    G_transmit('moocConfigList', {
        data: {
            moocId: route.params.moocId,
            configKey: 'mooc_must_evaluate' // 评价
        }
    }).then((res) => {
        if (res.data && res.data[0] && res.data[0].configValue && res.data[0].configValue == '1') {
            isNeedComment.value = true;
        }
        console.log( isNeedComment.value, ' isNeedComment.value isNeedComment.value isNeedComment.value isNeedComment.value isNeedComment.valuev');
    })
}

onBeforeUnmount(() => {
	window.removeEventListener('scroll', handleScroll)
})

watch(() => props.currentTab, async(newVal) => {
    await nextTick();
    if (newVal === currentTabKey.value) {
        getMoocConfig();
    }
}, {
    immediate: true
})

watch(() => props.detail, async(newVal) => {
    await nextTick();
    toFirstPage();
}, {
    immediate: true,
    deep: true
})

</script>

<style lang="scss" scoped>
.course-comment-container {
    margin: 30px 40px 30px 20px;
    .comment-header {
        font-size: 16px;
        font-family: MicrosoftYaHei-Bold, MicrosoftYaHei;
        font-weight: bold;
        color: #000000;
        line-height: 16px;
        span {
            font-weight: 400;
            font-family: MicrosoftYaHei;
            color: var(--srt-color-light-gray);
            margin-left: 4px;
        }
    }
    .mar-t10 {
        margin-top: 10px;
    }
    .divider-line {
        border-top: 1px solid #E0E2E4;
        margin: 30px 0;
    }
}
</style>